package com.anyikang.volunteer.sos.volunteer.app.main;
import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.MyApplication;
import com.anyikang.volunteer.sos.volunteer.app.MyConstant;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyCurrentOrder;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyRescueListData;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyRescueListItem;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyRescueListJson;
import com.anyikang.volunteer.sos.volunteer.app.bean.ReceiveOrderJson;
import com.anyikang.volunteer.sos.volunteer.app.bean.TaskOrder;
import com.anyikang.volunteer.sos.volunteer.app.bean.User;
import com.anyikang.volunteer.sos.volunteer.baidu.BaiduNavActivity;
import com.anyikang.volunteer.sos.volunteer.baidu.LocationService;
import com.anyikang.volunteer.sos.volunteer.baidu.OverlayManager;
import com.anyikang.volunteer.sos.volunteer.utils.BaiduMapUtils;
import com.anyikang.volunteer.sos.volunteer.utils.CommonUtil;
import com.anyikang.volunteer.sos.volunteer.utils.MyErrorDeal;
import com.anyikang.volunteer.sos.volunteer.utils.PermissionResultAdapter;
import com.anyikang.volunteer.sos.volunteer.utils.PermissionUtil;
import com.anyikang.volunteer.sos.volunteer.utils.ToastUtils;
import com.anyikang.volunteer.sos.volunteer.utils.Utils;
import com.anyikang.volunteer.sos.volunteer.utils.okhttputils_callback.StringDialogCallback;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.model.LatLng;
import com.baidu.navisdk.adapter.BNCommonSettingParam;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

import static com.anyikang.volunteer.sos.volunteer.app.MyApplication.hasInitSuccess;


/**
 * 首页
 * 
 */
public class HomeFragment extends Fragment implements SensorEventListener,View.OnClickListener {

	private View layout;

	//地图相关包括Marker
	private MapView mMapView;
	private BaiduMap mBaiduMap;
	private InfoWindow mInfoWindow;
	// 初始化全局 bitmap 信息，不用时及时 recycle
	// 定位相关
	static private LocationService locationService;

	BitmapDescriptor mCurrentMarker;

	private SensorManager mSensorManager;
	private Double lastX = 0.0;
	private int mCurrentDirection = 0;
	private double mCurrentLat = 0.0;  //我的当前位置
	private double mCurrentLng = 0.0;
	private float mCurrentAccracy;


	private MyLocationData locData;
	private float direction;
	private String TAG = "HomeFragment";


	BitmapDescriptor bdA = BitmapDescriptorFactory
			.fromResource(R.drawable.sosloc);
	BitmapDescriptor bdB = BitmapDescriptorFactory
			.fromResource(R.drawable.icon_markb);
	BitmapDescriptor bdC = BitmapDescriptorFactory
			.fromResource(R.drawable.icon_markc);
	BitmapDescriptor bdD = BitmapDescriptorFactory
			.fromResource(R.drawable.icon_markd);
	List<OverlayOptions> listOverlayOptions;

	//我的位置标记颜色
	private static final int accuracyCircleFillColor = 0xAAFFFF88;
	private static final int accuracyCircleStrokeColor = 0xAA00FF00;

	private Activity mActivity;
	private OverlayManager overlayManager;
	private ImageButton btMyLocation;




	//GXW FOR 多个points in screen
	List<OverlayOptions> mOverLayOptionList = new ArrayList<OverlayOptions>();

	//以下用于百度导航
	public static List<Activity> activityList = new LinkedList<Activity>();
	private String mSDCardPath = null;
	private static final String APP_FOLDER_NAME = "BNSDKVolunteer";

	private static final String[] authBaseArr = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.ACCESS_FINE_LOCATION};
	private static final int authBaseRequestCode = 1;
	private static final int authComRequestCode = 2;
	String authinfo = null;

	private boolean hasRequestComAuth = false;
	private static final String[] authComArr = {Manifest.permission.READ_PHONE_STATE};
	public static final String ROUTE_PLAN_NODE = "routePlanNode";

	/*gxw+s*/
	LinearLayout pushLayout;
	View mView;
	static  TaskOrder mTaskOrder;
	private List<TaskOrder> mTaskOrderList = new ArrayList();
	ProgressDialog progressDialog;
	//gxw-MyHomeReceiver myHomeReceiver = new MyHomeReceiver();


	//在背后不断请求 SOS呼救者的位置，这里顶一个timer和timerTask,handler结合实现定时任务
	private  Timer mTimerGetSosLocation = null;
	private TimerTask mTaskGetSosLocation;
	static private Handler mHandler;

	//定时定位在百度定位SDK里设置，所以定时定位任务不需自己写，只要获得位置后,向handler发送消息上传自己的位置到服务端
	private ImageButton ib_refresh;

	private final int GET_SOSLOC_FROM_DB = 1;
	private final int GET_SOSLOC_FROM_JPUSH = 2;

	//首页
	//gxw-private boolean isSkipFromTaskOrder = false;
	/*gxw+e*/

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {


	/*	if (mView != null) {
			ViewGroup parent = (ViewGroup) mView.getParent();
			if (parent != null) {
				parent.removeView(mView);
			}

			initView();
			initNav();//初始百度导航

			initMyLocation();

			return mView;
		}
		else
		{
			layout = null;
			layout = inflater.inflate(R.layout.fragment_home, container, false);
			mView = layout;
		}*/

		layout = inflater.inflate(R.layout.fragment_home, container, false);
		createHandler(); //用于处理定时任务器发过来的消息，比如 发消息通知主线程 调用获取位置的接口（从数据库里读取）
		Log.i(TAG, "onCreateView");
		getTaskState();
		initView();
		initMyLocation(); //初始化我的位置图标
		requestMyLocation();//请求我的位置
		//initNav();//初始百度导航
		mTimerGetSosLocation = new Timer();

		return layout;
	}

	/**
	 * 刚开始是把当前正在进行的任务单ID，状态等信息保存在本地SD卡，为了把稳一些，如果SD卡里没有存储，就去服务器
	 * 获取 志愿者当前有没有正在进行的救助任务，如果有那么就要开始不断获取SOS呼救人的位置并且不断上报自己的位置
	 */

	/**
	 * 获取成功
	 */
	public void  dealGetMyRecueSuccess(MyRescueListData data) {

		MyRescueListItem myRescuingItem;
		ArrayList<MyRescueListItem> myRescueListItem =  data.getList();
		if(myRescueListItem != null)
		{

			myRescuingItem = myRescueListItem.get(0);
			//保存接受的任务单 信息
			int state = myRescuingItem.getState();
			Log.i(TAG,"helping state="+state);
			MyCurrentOrder currentOrder = new MyCurrentOrder();
			ContentValues curOrderValues = new ContentValues();
			curOrderValues.put("itemId",myRescuingItem.getOrderId());
			curOrderValues.put("state",state);  //我在救助中
			curOrderValues.put("deviceIMEI",myRescuingItem.getDeviceIMEI());
			curOrderValues.put("sosPersonId",myRescuingItem.getSosPersonId());
			currentOrder.saveCurOrderInfo(mActivity,curOrderValues);//保存住当前接受的任务单，用于现场图片上传（先接单才上传）
			if(state == 2)
			{
				MyApplication.isRecvingOrder = true;
			}
			else
			{
				MyApplication.isRecvingOrder = false;
			}

			startRefreshSosLoc(); //启动刷新任务
		}

		return;

	}
	public void getTaskState()
	{

	/*gxw-s	testing MyCurrentOrder curOrder = new MyCurrentOrder(mActivity);
		String curOrderId = curOrder.getItemId();
		if(!TextUtils.isEmpty(curOrderId))  //如果本地存储有，则用本地存储的，目前任务完成只能是在APP上触发，因此本地存储里的任务单也是最新的状态，无需请求服务器
		{
			int state = curOrder.getState();

			if(state == 2) //正在救助中
			{
				MyApplication.isRecvingOrder = true;
			}
			else
			{
				MyApplication.isRecvingOrder = false;
			}
			return;
		}gxw-e*/

		//查询志愿者 正在救助中的 任务单
		User user = new User(mActivity);
		String token = user.getUserToken();
		int state = 0;  //0查询全部,2未完成（救助中），3已完成，4报告已提交，查询2是为了查询当前志愿者是否有正在救援中的任务，如果有就要刷新SOS位置并且上报自己的位置
		Log.i(TAG,"url ="+ MyConstant.API_MY_SOS_LIST + "token="+token+",state="+state+",pageIndex="+1+",pageSize="+1);
		OkHttpUtils
				.get(MyConstant.API_MY_SOS_LIST)//
				.tag(MyConstant.API_MY_SOS_LIST)//
				.params("tokenId", token)//
				.params("state",String.valueOf(state))
				.params("pageIndex",String.valueOf(1))   //因为志愿者只能和一个正在救助中的任务单关联，所以页码pageIndex=1且pageSize=1就足够了
				.params("pageSize",String.valueOf(1))
				.params("sortType",String.valueOf(1))  //按时间排序
				.execute(new StringDialogCallback(mActivity) {
					@Override
					public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

						int retCode = response.code();
						if(retCode == 200)
						{
							Log.i(TAG,"onSuccess 200 return："+s);
							try
							{
								MyRescueListJson myRescueListJson = new Gson().fromJson(s,MyRescueListJson.class);

								if(myRescueListJson.getStatus() == 1)//查询全部成功
								{
									//
									dealGetMyRecueSuccess(myRescueListJson.getData());
								}
								else {
									String msg = myRescueListJson.getMsg();
									MyErrorDeal.dealError(msg,mActivity);
								}
							}
							catch (Exception e)
							{
								e.printStackTrace();
							}
						}
						else
						{
							MyErrorDeal.dealHttpError(response,mActivity);
							Log.i(TAG,"onSuccess "+retCode+"return: "+s);
						}
					}

					@Override
					public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {


						MyErrorDeal.dealHttpError(response,mActivity);

					}
				});

	}

	public void initMyLocation()
	{

		mCurrentMarker = BitmapDescriptorFactory
				.fromResource(R.drawable.icon_geo);
         /*   mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
					MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker,
                    accuracyCircleFillColor, accuracyCircleStrokeColor));*/

		mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
				MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker));  //gxw modify to normal ,follow是带风向的跟踪
		MapStatus.Builder builder = new MapStatus.Builder();
		builder.overlook(0);
		MapStatusUpdate  update = MapStatusUpdateFactory.newMapStatus(builder.build());
		mBaiduMap.animateMapStatus(update);
		mBaiduMap.setMyLocationEnabled(true);

		return;
	}

	/**
	 * 传递自己的位置（志愿者的位置）到服务器
	 */
	public void postMyLocation(String lat,String lng)
	{
		User user = new User(mActivity);
		String token = user.getUserToken();
        long locationTime = System.currentTimeMillis();

		Log.i(TAG,"URL="+MyConstant.API_POST_MY_LOCATION+",token="+token+",latitude="+lat+",longitude="+lng);
		OkHttpUtils
				.post(MyConstant.API_POST_MY_LOCATION)//
				.tag(MyConstant.API_POST_MY_LOCATION )//
				.params("tokenId", token)//
				.params("latitude",lat)
				.params("longitude",lng)
				.params("locationTime",String.valueOf(locationTime))
				.execute(new StringCallback() {
					@Override
					public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

						int retCode = response.code();
						if(retCode == 200)
						{
							Log.i(TAG,"onSuccess 200 return："+s);
							try
							{
								JSONObject postMyLoc = new JSONObject(s);
								if(postMyLoc.getString("status").equals("1"))  //成功响应
								{
							        Log.i(TAG,"上传我的位置成功");
									ToastUtils.showToast(mActivity,"上传我的位置成功");
									Vibrator vib = (Vibrator) mActivity.getSystemService(Service.VIBRATOR_SERVICE);
									vib.vibrate(1000);
								}

							}
							catch (Exception e)
							{
								e.printStackTrace();
							}
						}
						else
						{
							MyErrorDeal.dealHttpError(response,mActivity);
							Log.i(TAG,"onSuccess "+retCode+"return: "+s);
						}
					}

					@Override
					public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

						MyErrorDeal.dealHttpError(response,mActivity);

					}
				});
		return;
	}

	private void createHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what)
				{
					case 0:       //上传自己的位置到服务端

                        Bundle b = msg.getData();

						if(b != null)
						{
							double lat = b.getDouble("lat");
							double lng = b.getDouble("lng");
							mCurrentLat = lat;
							mCurrentLng = lng;
							float currentAccracy = b.getFloat("accracy");
							boolean isCenterMyLoc = b.getBoolean("isCenterMyLoc");

							locData = new MyLocationData.Builder()
									.accuracy(currentAccracy)
									// 此处设置开发者获取到的方向信息，顺时针0-360
									.direction(mCurrentDirection).latitude(lat)
									.longitude(lng).build();
							mBaiduMap.setMyLocationData(locData);


							if(isCenterMyLoc)
							{
								LatLng baiduLatLng = new LatLng(lat, lng);
								MapStatus.Builder builder = new MapStatus.Builder();
								//gxw-builder.target(ll).zoom(14.0f);
								builder.target(baiduLatLng);
								mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
							}



							postMyLocation(String.valueOf(lat),String.valueOf(lng));
						}
						break;
					case 1:      //背后读取数据库位置
						refreshSosLocation(GET_SOSLOC_FROM_DB);
						break;

					case 2:  //询问志愿者位置
						addMyLocationLayer();

						break;
					case 3:

						Bundle b1 = msg.getData();

						if(b1 != null)
						{
							String extraJsonStr = b1.getString("sosLoc");
									Log.i("MyHomeReceiver","jpush sos location extra="+extraJsonStr);
							mTaskOrder = new Gson().fromJson(extraJsonStr,TaskOrder.class);
							updateSosLocationGui();
						}

						break;

				}

				// 要做的事情
				super.handleMessage(msg);
			}
		};
	}


	/**
	 * 创建定时任务，不断请求服务端数据库里的SOS位置
	 * @return
	 */
	public  TimerTask createTaskGetSosLocation()
	{
		TimerTask taskGetSosLocation = new TimerTask() {
			@Override
			public void run() {

				MyCurrentOrder currentOrder = new MyCurrentOrder(mActivity);
				if(currentOrder.getState() == 2)  //只有在接收救援，订单状态变为2救助中，才在背后不断更新地图上的SOS位置
				{
					mHandler.sendEmptyMessage(1);//从数据库里读取位置

				}
				else  //一旦发现任务单已完成取消刷新实时位置
				{
					cancelRefreshSosloc();
				}

			}
		};

		return taskGetSosLocation;
	}


	@Override
	public void onHiddenChanged(boolean hidden) {

		Log.i(TAG,"onHiddenChanged="+hidden);
		if(hidden == false) {   //show


			startRefreshSosLoc();

			if(overlayManager != null)
			{
				overlayManager.zoomToSpan();  //用于从其它TAB切换回地图页面时，居中求救人的位置到地图中心
			}

		}
		else
		{
			cancelRefreshSosloc();
		}

		super.onHiddenChanged(hidden);
	}


	/**
	 * 定时任务从数据库里 获取SOS位置
	 */
	public void startRefreshSosLoc()
	{
	/*
			   如果已经接单且状态为2救助中时，启动后台定时任务，不断更新SOS求救人的位置。MyCurrentOrder的数据是从本地存储里读取的，有一定的持久性，即使退出APP，
			   当第二次打开APP时依然能读取到当前是否在救助中，从而判断是否要启动定时任务去不断更新SOS求救人的位置
			   */
		MyCurrentOrder curOrder = new MyCurrentOrder(mActivity);
		String curOrderId = curOrder.getItemId();
		int state = curOrder.getState();

	/*gxw-s
	String deviceIMEI = curOrder.getDeviceIMEI();
	if(mTaskOrder == null)   //如果退出应用后再进来，用本地持久存储对象MyCurrentOrder来初始化当前接受的任务mTaskOrder
		{
			mTaskOrder = new TaskOrder();
			mTaskOrder.setItemId(curOrderId);
			mTaskOrder.setState(state);
			mTaskOrder.setDeviceIMEI(deviceIMEI);
		}gxw-e*/

		if(!TextUtils.isEmpty(curOrderId) && state == 2)  //1需要救助即未接单，2救助中，3已完成
		{
			MyApplication.isRecvingOrder = true; //已接单并正在救助中


			if(mTimerGetSosLocation != null)
			{
				if(mTaskGetSosLocation != null)
				{
					mTaskGetSosLocation.cancel();
				}
			}
			else
			{
				mTimerGetSosLocation = new Timer();
			}
			mTaskGetSosLocation = createTaskGetSosLocation();
			mTimerGetSosLocation.schedule(mTaskGetSosLocation,3000,15000); //开始执行定时任务，每隔1分钟请求一次 type=1从服务器数据库里返回位置
		}
		else
		{
			MyApplication.isRecvingOrder = false;
			//clearMarker();
		}

	}

	/**
	 *
	 *  取消获取SOS位置从数据库
	 */
	public void cancelRefreshSosloc()
	{
		if(mTaskGetSosLocation != null)
		{
			mTaskGetSosLocation.cancel();  //取消任务
			mTaskGetSosLocation = null;

		}
		if(mTimerGetSosLocation != null) {
			mTimerGetSosLocation.cancel();  //取消定时器
			mTimerGetSosLocation = null;
		}
	}


	@Override
	public void onStart() {
		Log.i(TAG,"onStart");
		//gxw-已改为XML里的静态广播registSosLocationBroadcast();
		startRefreshSosLoc();  //  当第一次进入APP首页时，如果我接了任务单且状态为救助中2时，因为刚进入首页不执行onhidden函数，因此在这里要启动刷新SOS位置
		addMyLocationLayer();
		super.onStart();
	}

	@Override
	public void onResume() {
		//gxw-OnMapLoadedCallbackShowMarkers();
		Log.i(TAG,"onResume");
		//gxw-mMapView.onResume();
		//gxw-addMyLocationLayer();
/*		mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SensorManager.SENSOR_DELAY_UI);*/

		super.onResume();
		//为系统的方向传感器注册监听器
	}

	@Override
	public void onPause() {
		Log.i(TAG,"onPause");
		//mMapView.onPause();
		super.onPause();
	}

	@Override
	public void onStop() {

		//取消注册传感器监听
		Log.i(TAG,"onStop");
		cancelRefreshSosloc(); //页面隐藏后就不要刷新SOS位置了，但是还能询问志愿者位置，因此myHomeReceiver监听器不能在这里注销
		mSensorManager.unregisterListener(this);
		super.onStop();
	}
	@Override
	public void onDestroy() {
		// 退出时销毁定位
		Log.i(TAG,"onDestroy");

		MyApplication.isSkipFromTaskOrder = false;

		/**
		 * APP退出了让继续监听志愿者位置(MyApplication里发送过来的广播)，因此在这里不注销这个广播接收器。
		 */
	//gxw-	mActivity.unregisterReceiver(myHomeReceiver);



		/*gxw-
               这里有个问题，当推送收到新任务单后，会导致onDestroy函数执行，之前的locationservice就stop了，就停止上报志愿者（自己）的位置了，
		       因此当志愿者有任务单处在救援中时，服务端不应再推送任务单给这个志愿者了,现在为了防止服务端BUG
		       暂时屏蔽掉locationService.stop和 unrigisterListener(mListener)。
		locationService.unregisterListener(mListener); //停止定位
		locationService.stop();
	    Log.i(TAG,"stop loc service in onDestroy");
	    gxw-e

	    */


		mBaiduMap.setMyLocationEnabled(false);	// 关闭定位图层
		mMapView.onDestroy();
		mMapView = null;

		super.onDestroy();
	}


	/**
	 * 初始化百度导航
	 */
	private void initNav() {

		//gxw-initSetting();
		if (initDirs()) {
			initNavi();
		}
	}

	@Override
	public void onAttach(Context context) {
		Log.i(TAG, "onAttach");
		mActivity = (Activity) context;
		super.onAttach(context);
	}

	 public void initLocServiceAndStart()
	{
		locationService = ((MyApplication) mActivity.getApplication()).locationService;
		locationService.start();
	}



	public void addMarker()
	{
		initOverlay();
	}



	/**
	 * 启动定位，我的位置
	 */
	 public void addMyLocationLayer()
	{
		// 开启定位图层
		//gxw-mBaiduMap.setMyLocationEnabled(true);
		initLocServiceAndStart();
	}

	public void requestMyLocation()
	{

		locationService = ((MyApplication) mActivity.getApplication()).locationService;//testing
		locationService.start();
		locationService.getClient().requestLocation();//实时请求，不受定位间隔管控
	}

	/**
	 * 获得其它组件传递过来的intent数据
	 */
	public void getLastIntent()
	{

		Intent intent = mActivity.getIntent();
		if(intent != null)
		{
			Bundle bundle = intent.getExtras();
			if(bundle != null)
			{


					//gxw- testing addMyLocationLayer();  //更新我的位置


				String msgTitle = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);

				if (!TextUtils.isEmpty(msgTitle)) {

					MyApplication.isSkipFromTaskOrder = true;

					String alertNotify = bundle.getString(JPushInterface.EXTRA_ALERT);  //通知栏内容
					TextView tvAlert = (TextView) pushLayout.findViewById(R.id.tvJpushAlert);
					tvAlert.setText(alertNotify); //推送的通知内容

					String msgExtra = bundle.getString(JPushInterface.EXTRA_EXTRA);    //附加数据

					Log.i(TAG+"extra", msgExtra);
					try {

						JSONObject extraObj = new JSONObject(msgExtra);
						JSONObject data = extraObj.getJSONObject("jsonExtra");

						mTaskOrder = new Gson().fromJson(data.toString(), TaskOrder.class);

						String lat = mTaskOrder.getLatitude();
						String lng = mTaskOrder.getLongitude();

						if (!TextUtils.isEmpty(lat) && !TextUtils.isEmpty(lng))
						{
							pushLayout.setVisibility(View.VISIBLE);
							//将GPS坐标转换为百度坐标类型
							double doubleLat = Double.parseDouble(lat);
							double doubleLng = Double.parseDouble(lng);
							LatLng baiduLatLng = BaiduMapUtils.convertGps2Map(doubleLat,doubleLng);
							mTaskOrder.setLatitude(String.valueOf(baiduLatLng.latitude));   //设置为百度地图类型的坐标
							mTaskOrder.setLongitude(String.valueOf(baiduLatLng.longitude));

							updateSosLocationGui();
						}
						else
						{
							Log.i(TAG,"经纬度为空");
						}



					} catch (Exception e) {
						e.printStackTrace();
					}


				}
				else   //呼救列表传递过来的
                {
					MyApplication.isSkipFromTaskOrder = true;
					pushLayout.setVisibility(View.VISIBLE);

					mTaskOrder = (TaskOrder) bundle.getSerializable("taskOrder");

					//将GPS坐标转换为百度坐标类型
					double lat = Double.parseDouble(mTaskOrder.getLatitude());
					double lng = Double.parseDouble(mTaskOrder.getLongitude());
					LatLng baiduLatLng = BaiduMapUtils.convertGps2Map(lat,lng);
					mTaskOrder.setLatitude(String.valueOf(baiduLatLng.latitude));   //设置为百度地图类型的坐标
					mTaskOrder.setLongitude(String.valueOf(baiduLatLng.longitude));

					String address = mTaskOrder.getAddress();
					String name = mTaskOrder.getName();

					TextView tvAlert = (TextView) pushLayout.findViewById(R.id.tvJpushAlert);
					String alert = "来自"+address+"的"+name+"需要救援，是否去救援？";

					tvAlert.setText(alert); //推送的通知内容
					updateSosLocationGui();
                }
			}

		}



		return;
	}
	/**
	 * 初始化控件 n
	 */
	private void initView() {

		mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);//获取传感器管理服务
		//Map
		mMapView = (MapView) layout.findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();

		//Marker单击响应
		mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
			public boolean onMarkerClick(final Marker marker) {
				overlayManager.onMarkerClick(marker);
				return true;
			}
		});

		/**
		 * 监听地图触摸，取消气泡
		 */
		mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
			@Override
			public void onTouch(MotionEvent motionEvent) {

				if(motionEvent.getAction() == MotionEvent.ACTION_UP)
				{
					mBaiduMap.hideInfoWindow();
				}
			}
		});

		//让分布在不同地区的marker显示在同一视野里
		mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
			@Override
			public void onMapLoaded() {
				overlayManager = newOverlayManager();
				//根据marker分布自适应缩放地图
				overlayManager.addToMap(mTaskOrderList);
				overlayManager.zoomToSpan();

			}
		});
		clearMarker();

		//刷新求救人的位置
		ib_refresh = (ImageButton) layout.findViewById(R.id.ib_refresh);
		ib_refresh.setOnClickListener(this);


		//MyLocation
		btMyLocation = (ImageButton) layout.findViewById(R.id.btMyLocation);
		btMyLocation.setOnClickListener(this);

		pushLayout = (LinearLayout) layout.findViewById(R.id.pushLayout);


		Button btSureRescue = (Button) pushLayout.findViewById(R.id.sureRescue);
		btSureRescue.setOnClickListener(this);


		Button btCancelRescue = (Button) pushLayout.findViewById(R.id.cancelRescue);
		btCancelRescue.setOnClickListener(this);

		//每当地图加载完成时，重新显示多个marker到同一视野,marker的单击事件也在这里处理
	//	OnMapLoadedCallbackShowMarkers();

		getLastIntent();  //获得推送下来的通知内容，经纬度、地址等信息。
	}


	private boolean hasBasePhoneAuth() {
		// TODO Auto-generated method stub

		PackageManager pm = mActivity.getPackageManager();
		for (String auth : authBaseArr) {
			if (pm.checkPermission(auth, mActivity.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
				return false;
			}
		}
		return true;
	}


	private boolean hasCompletePhoneAuth() {
		// TODO Auto-generated method stub

		PackageManager pm = mActivity.getPackageManager();
		for (String auth : authComArr) {
			if (pm.checkPermission(auth, mActivity.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
				return false;
			}
		}
		return true;
	}

	private BNRoutePlanNode.CoordinateType mCoordinateType = null;

	private void routeplanToNavi(BNRoutePlanNode.CoordinateType coType,LatLng latlang) {
		mCoordinateType = coType;
		if (!MyApplication.hasInitSuccess) {
			Log.i(TAG,"还未初始化");
			Toast.makeText(mActivity, "还未初始化!", Toast.LENGTH_SHORT).show();
		}
		// 权限申请
		if (android.os.Build.VERSION.SDK_INT >= 23) {

			Log.i(TAG,"请求权限");
			// 保证导航功能完备
			if (!hasCompletePhoneAuth()) {
				if (!hasRequestComAuth) {
					hasRequestComAuth = true;
					this.requestPermissions(authComArr, authComRequestCode);
					return;
				} else {
					Toast.makeText(mActivity, "没有完备的权限!", Toast.LENGTH_SHORT).show();
				}
			}
		}

		BNRoutePlanNode sNode = null;
		BNRoutePlanNode eNode = null;
		switch (coType) {
			case GCJ02: {

				Log.i(TAG," GCJ02 sNode and eNode");
				sNode = new BNRoutePlanNode(116.30142, 40.05087, "百度大厦", null, coType);
				eNode = new BNRoutePlanNode(116.39750, 39.90882, "北京天安门", null, coType);
				break;
			}
			case WGS84: {

				//gxw-sNode = new BNRoutePlanNode(116.300821, 40.050969, "百度大厦", null, coType);

				if(mTaskOrder != null)
				{
					if(mCurrentLat == 0.0)
					{
						ToastUtils.showToast(mActivity,"请点击我的位置，先获取当前位置");
						return;
					}
					Log.i(TAG," WGS84 sNode and eNode"+",startLat="+mCurrentLat+",startLng="+mCurrentLng+",endLat="+mTaskOrder.getLatitude()+",endLng="+mTaskOrder.getLongitude());
					sNode = new BNRoutePlanNode(Double.parseDouble(mTaskOrder.getLongitude()), Double.parseDouble(mTaskOrder.getLatitude()), mTaskOrder.getAddress(), null, coType);
					eNode = new BNRoutePlanNode(mCurrentLng, mCurrentLat, "北京天安门", null, coType);
				}
				else
				{
					ToastUtils.showToast(mActivity,"没有目的地");
					return;
				}

				break;
			}
			case BD09_MC: {

				Log.i(TAG," BD09_MC sNode and eNode");
				sNode = new BNRoutePlanNode(12947471, 4846474, "百度大厦", null, coType);
				eNode = new BNRoutePlanNode(12958160, 4825947, "北京天安门", null, coType);
				break;
			}
			case BD09LL: {

				if(mTaskOrder != null)
				{
					if(mCurrentLat == 0.0)
					{
						ToastUtils.showToast(mActivity,"请点击我的位置，先获取当前位置");
						return;
					}
					Log.i(TAG," BD09LL sNode and eNode"+",startLat="+mCurrentLat+",startLng="+mCurrentLng+",endLat="+latlang.latitude+",endLng="+latlang.longitude);
					eNode = new BNRoutePlanNode(latlang.longitude, latlang.latitude, mTaskOrder.getAddress(), null, coType);
					sNode = new BNRoutePlanNode(mCurrentLng, mCurrentLat, "我的位置", null, coType);
				}
				else
				{
					ToastUtils.showToast(mActivity,"没有目的地");
				}
				break;
			}
			default:
				;
		}
		if (sNode != null && eNode != null) {
			List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
			list.add(sNode);
			list.add(eNode);
			Log.i(TAG," will launchNavigator");


			BaiduNaviManager.getInstance().launchNavigator(mActivity, list, 1, true, new DemoRoutePlanListener(sNode));
		}
	}

	public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

		private BNRoutePlanNode mBNRoutePlanNode = null;

		public DemoRoutePlanListener(BNRoutePlanNode node) {
			mBNRoutePlanNode = node;
			progressDialog = new ProgressDialog(mActivity);
			progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("路径规划中，请稍后...");
			progressDialog.show();

		}

		@Override
		public void onJumpToNavigator() {

			if(progressDialog != null)
			progressDialog.dismiss();
            /*
             * 设置途径点以及resetEndNode会回调该接口
             */
			Log.i(TAG," START activityList");
			for (Activity ac : activityList) {

				if (ac.getClass().getName().endsWith("BaiduNavActivity")) {
					return;
				}
			}

			Log.i(TAG," START BaiduNavActivity");
			//gxw-Intent intent = new Intent(mActivity, BNDemoGuideActivity.class);
			Intent intent = new Intent(mActivity, BaiduNavActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("sosPersonId",mTaskOrder.getSosPersonId());  //接单后，才会下发sosPersonId
			bundle.putString("taskItemId",mTaskOrder.getItemId());
			bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
			intent.putExtras(bundle);
			startActivity(intent);

		}

		@Override
		public void onRoutePlanFailed() {
			// TODO Auto-generated method stub
			if(progressDialog != null)
				progressDialog.dismiss();
			Toast.makeText(mActivity, "算路失败", Toast.LENGTH_SHORT).show();
		}
	}

	private void initSetting() {
		// BNaviSettingManager.setDayNightMode(BNaviSettingManager.DayNightMode.DAY_NIGHT_MODE_DAY);
		BNaviSettingManager
				.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
		BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
		// BNaviSettingManager.setPowerSaveMode(BNaviSettingManager.PowerSaveMode.DISABLE_MODE);
		BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
		Bundle bundle = new Bundle();
		// 必须设置APPID，否则会静音
		bundle.putString(BNCommonSettingParam.TTS_APP_ID, "9810446");
		BNaviSettingManager.setNaviSdkParam(bundle);
	}


	private BNOuterTTSPlayerCallback mTTSCallback = new BNOuterTTSPlayerCallback() {

		@Override
		public void stopTTS() {
			// TODO Auto-generated method stub
			Log.e("test_TTS", "stopTTS");
		}

		@Override
		public void resumeTTS() {
			// TODO Auto-generated method stub
			Log.e("test_TTS", "resumeTTS");
		}

		@Override
		public void releaseTTSPlayer() {
			// TODO Auto-generated method stub
			Log.e("test_TTS", "releaseTTSPlayer");
		}

		@Override
		public int playTTSText(String speech, int bPreempt) {
			// TODO Auto-generated method stub
			Log.e("test_TTS", "playTTSText" + "_" + speech + "_" + bPreempt);

			return 1;
		}

		@Override
		public void phoneHangUp() {
			// TODO Auto-generated method stub
			Log.e("test_TTS", "phoneHangUp");
		}

		@Override
		public void phoneCalling() {
			// TODO Auto-generated method stub
			Log.e("test_TTS", "phoneCalling");
		}

		@Override
		public void pauseTTS() {
			// TODO Auto-generated method stub
			Log.e("test_TTS", "pauseTTS");
		}

		@Override
		public void initTTSPlayer() {
			// TODO Auto-generated method stub
			Log.e("test_TTS", "initTTSPlayer");
		}

		@Override
		public int getTTSState() {
			// TODO Auto-generated method stub
			Log.e("test_TTS", "getTTSState");
			return 1;
		}
	};

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		// TODO Auto-generated method stub
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if (requestCode == authBaseRequestCode) {
			for (int ret : grantResults) {
				if (ret == 0) {
					continue;
				} else {
					Toast.makeText(mActivity, "缺少导航基本的权限!", Toast.LENGTH_SHORT).show();
					return;
				}
			}
			initNavi();
		} else if (requestCode == authComRequestCode) {
			for (int ret : grantResults) {
				if (ret == 0) {
					continue;
				}
			}

			double lat = Double.parseDouble(mTaskOrder.getLatitude());
			double lng = Double.parseDouble(mTaskOrder.getLongitude());
			LatLng latLng = new LatLng(lat,lng);
			routeplanToNavi(mCoordinateType,latLng);
		}

	}
	private void initNavi() {

		BNOuterTTSPlayerCallback ttsCallback = null;

		// 申请权限
		if (android.os.Build.VERSION.SDK_INT >= 23) {

			if (!hasBasePhoneAuth()) {

				this.requestPermissions(authBaseArr, authBaseRequestCode);
				return;

			}
		}

		BaiduNaviManager.getInstance().init(mActivity, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
			@Override
			public void onAuthResult(int status, String msg) {
				if (0 == status) {
					authinfo = "key校验成功!";
				} else {
					authinfo = "key校验失败, " + msg;
				}

				Log.i(TAG,authinfo);
		/*gxw-s		mActivity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Log.i(TAG,authinfo);
						Toast.makeText(mActivity, authinfo, Toast.LENGTH_LONG).show();
					}
				});gxw-e*/
			}

			public void initSuccess() {
				//gxw-Toast.makeText(mActivity, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
				Log.i(TAG,"百度导航引擎初始化成功");
				hasInitSuccess = true;
				initSetting();
			}

			public void initStart() {
				Log.i(TAG,"百度导航引擎初始化开始");
				//gxw-Toast.makeText(mActivity, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
			}

			public void initFailed() {
				Log.i(TAG,"百度导航引擎初始化失败");
				Toast.makeText(mActivity, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
			}

		}, null, ttsHandler, ttsPlayStateListener);

	}


	/**
	 * 内部TTS播报状态回调接口
	 */
	private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

		@Override
		public void playEnd() {
			// showToastMsg("TTSPlayStateListener : TTS play end");
		}

		@Override
		public void playStart() {
			// showToastMsg("TTSPlayStateListener : TTS play start");
		}
	};

	/**
	 * 内部TTS播报状态回传handler
	 */
	private Handler ttsHandler = new Handler() {
		public void handleMessage(Message msg) {
			int type = msg.what;
			switch (type) {
				case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
					// showToastMsg("Handler : TTS play start");
					break;
				}
				case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
					// showToastMsg("Handler : TTS play end");
					break;
				}
				default:
					break;
			}
		}
	};
	private boolean initDirs() {
		mSDCardPath = Utils.getSdcardDir();
		if (mSDCardPath == null) {
			return false;
		}
		File f = new File(mSDCardPath, APP_FOLDER_NAME);
		if (!f.exists()) {
			try {
				f.mkdir();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}


	/**
	 * 新建overlayManager
	 * @return
	 */
	public OverlayManager newOverlayManager()
	{
		OverlayManager overlayManager = new OverlayManager(mBaiduMap) {

			@Override
			public boolean onPolylineClick(Polyline polyline) {
				return false;
			}

			@Override
			public boolean onMarkerClick(final Marker marker) {   //marker单击事件，最终回调到这里

				View popView = mActivity.getLayoutInflater().inflate(R.layout.baidu_pop, null);
				Button imgBtNav = (Button) popView.findViewById(R.id.imgBtNav);
				TextView tvName = (TextView) popView.findViewById(R.id.tvName);
				TextView tvAddress = (TextView) popView.findViewById(R.id.tvAddress);
				TextView tvSosLocTime = (TextView) popView.findViewById(R.id.tvSosLocTime);

				Bundle b = marker.getExtraInfo();
				String deviceIMEI, name = "", loctime, address = "";

				double lat = 0.0;
				double lng = 0.0;

				LatLng latlng = null;
				if (b != null) {
					deviceIMEI = b.getString("deviceIMEI");
					lat =  b.getDouble("lat");
					lng = b.getDouble("lng");
					latlng = new LatLng(lat,lng);
					name = b.getString("name");
					address = b.getString("address");
					Log.i(TAG, "imei=" + deviceIMEI + ",lat=" + lat + ",lng=" + lng + ",name=" + name);

					if(!TextUtils.isEmpty(name))
					{
						tvName.setText(name);
					}

					if(!TextUtils.isEmpty(address))
					{
						tvAddress.setText(address);
					}

					String sosLocTimeRight = b.getLong("sosTime")+"";
					String strSosLocTime = CommonUtil.getDateTimeYmdHms(Long.parseLong(sosLocTimeRight));


					if(!TextUtils.isEmpty(strSosLocTime))
					{
						tvSosLocTime.setText(strSosLocTime);
					}
				}

				final LatLng sosLocation = new LatLng(lat,lng); //已经是百度坐标类型了

				imgBtNav.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						mBaiduMap.hideInfoWindow();
						//gxw-Toast.makeText(mActivity,"点击了导航",Toast.LENGTH_SHORT).show();

						Log.i(TAG,"点击了导航");
                             /*   Intent i = new Intent(mActivity, BaiduNavActivity.class);
                                startActivity(i);
                             */

						if (BaiduNaviManager.isNaviInited()) {
							routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL, sosLocation);  //原生GPS坐标类型
						}
					}
				});

				popView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						mBaiduMap.hideInfoWindow();
					}
				});


				mInfoWindow = new InfoWindow(popView, sosLocation, -47);
				mBaiduMap.showInfoWindow(mInfoWindow);

				return true;
			}

			@Override
			public List<OverlayOptions> getOverlayOptions() {
				return mOverLayOptionList;
			}

		};
		return overlayManager;
	}
	/**
	 * 每当地图加载完成时，重新显示多个marker到同一视野
	 */
	private void OnMapLoadedCallbackShowMarkers() {





		/**
		 * 监听地图触摸，取消气泡
		 */
	/*	mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() {
			@Override
			public void onTouch(MotionEvent motionEvent) {

				if(motionEvent.getAction() == MotionEvent.ACTION_UP)
				{
					mBaiduMap.hideInfoWindow();
				}
			}
		});*/

	/*	//让分布在不同地区的marker显示在同一视野里
		mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
			@Override
			public void onMapLoaded() {
				overlayManager = newOverlayManager();
				//根据marker分布自适应缩放地图
				overlayManager.addToMap(mTaskOrderList);
				overlayManager.zoomToSpan();



			}
		});*/
	}


	private void callPhone() {
		//6.0权限申请
		PermissionUtil.getInstance().request(mActivity, new String[]{PermissionUtil.PERMISSION_CALL_PHONE}, new PermissionResultAdapter() {

			public void onPermissionGranted() {
				// 拨号：激活系统的拨号组件
				Intent intent = new Intent(); // 意图对象：动作 + 数据
				intent.setAction(Intent.ACTION_CALL); // 设置动作

				Uri data = Uri.parse("tel:" + "13072925248"); // 设置数据
				intent.setData(data);
				mActivity.startActivity(intent); // 激活Activity组件
			}


			public void onPermissionDenied(String... permissions) {
				Toast.makeText(mActivity,"请打开打电话权限",Toast.LENGTH_SHORT).show();
			}
		});

	}



    public void initOverlay() {
        //模拟4个点，其中D点 是求救的人

		/*gxw-s
		LatLng llA = new LatLng(39.963175, 116.400244);
        LatLng llB = new LatLng(39.942821, 116.369199);//北京
        LatLng llC = new LatLng(39.939723, 116.425541);//北京gxw-e*/


		/*gxw-s
		//A
       final MarkerOptions ooA = new MarkerOptions().position(llA).icon(bdA)
                .zIndex(9).draggable(true);
		// 掉下动画
		ooA.animateType(MarkerOptions.MarkerAnimateType.drop);

		mOverLayOptionList.add(ooA);


		//B
        MarkerOptions ooB = new MarkerOptions().position(llB).icon(bdB)
                .zIndex(9);
		// 掉下动画
		ooB.animateType(MarkerOptions.MarkerAnimateType.drop);
		mOverLayOptionList.add(ooB);

		//C
        MarkerOptions ooC = new MarkerOptions().position(llC).icon(bdC)
                .perspective(false).anchor(0.5f, 0.5f).rotate(30).zIndex(9);
		// 生长动画
		ooC.animateType(MarkerOptions.MarkerAnimateType.grow);
		mOverLayOptionList.add(ooC);gxw-e*/


		//D
		mTaskOrderList.add(mTaskOrder);

		//目前就这一个点
		double lat = Double.parseDouble(mTaskOrder.getLatitude());
		double lng = Double.parseDouble(mTaskOrder.getLongitude());

		LatLng markerLatLng = new LatLng(lat, lng);//已经在推送getIntent里将GPS坐标转换成了百度坐标了，在这里无需转换了

		//动画demo
        ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
        giflist.add(bdA);
        giflist.add(bdB);
        giflist.add(bdC);

/*gxw-s	暂时不需要gif动画	MarkerOptions ooD = new MarkerOptions().position(convertLatLng).icons(giflist)
				.zIndex(9).period(10);gxw-e*/
        MarkerOptions ooD = new MarkerOptions().position(markerLatLng).icon(bdA)
                .zIndex(9).period(10);
		// 生长动画
		ooD.animateType(MarkerOptions.MarkerAnimateType.grow);
		mOverLayOptionList.add(ooD);


		if(overlayManager == null)
		{
			overlayManager = newOverlayManager();

		}
		overlayManager.addToMap(mTaskOrderList);
		overlayManager.zoomToSpan();

		//Marker拖曳
        mBaiduMap.setOnMarkerDragListener(new BaiduMap.OnMarkerDragListener() {
            public void onMarkerDrag(Marker marker) {
            }

            public void onMarkerDragEnd(Marker marker) {
                Toast.makeText(getActivity()
                        ,
                        "拖拽结束，新位置：" + marker.getPosition().latitude + ", "
                                + marker.getPosition().longitude,
                        Toast.LENGTH_LONG).show();
            }

            public void onMarkerDragStart(Marker marker) {
            }
        });


    }

	@Override
	public void onSensorChanged(SensorEvent sensorEvent) {
		double x = sensorEvent.values[SensorManager.DATA_X];
		if (Math.abs(x - lastX) > 1.0) {
			mCurrentDirection = (int) x;
			locData = new MyLocationData.Builder()
					.accuracy(mCurrentAccracy)
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(mCurrentDirection).latitude(mCurrentLat)
					.longitude(mCurrentLng).build();
		mBaiduMap.setMyLocationData(locData);
		}
		lastX = x;
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int i) {

	}

	/**
     * 处理接单成功
     */
	public void dealRecvOrderOk(TaskOrder data)
	{
		String itemId = data.getItemId();
		String sosPersonId = data.getSosPersonId();
		String deviceIMEI = data.getDeviceIMEI();
        double latitude = Double.parseDouble(data.getLatitude());  //gps坐标
		double longitude = Double.parseDouble(data.getLongitude());


        //因为接单的瞬间，求救人的位置会有变化，因此要刷新mTaskOrder中的经纬度等值（要gps转百度）
        LatLng baiduLatlng = BaiduMapUtils.convertGps2Map(latitude,longitude); //转换为百度坐标
		mTaskOrder.setItemId(itemId);
		mTaskOrder.setSosPersonId(sosPersonId);
		mTaskOrder.setDeviceIMEI(deviceIMEI);
        mTaskOrder.setLatitude(String.valueOf(baiduLatlng.latitude));
        mTaskOrder.setLongitude(String.valueOf(baiduLatlng.longitude));

        //保存接受的任务单 信息
		MyCurrentOrder currentOrder = new MyCurrentOrder();
		ContentValues curOrderValues = new ContentValues();
		curOrderValues.put("itemId",itemId);
		curOrderValues.put("state",2);  //我在救助中
		curOrderValues.put("deviceIMEI",deviceIMEI);
		curOrderValues.put("sosPersonId",sosPersonId);
		currentOrder.saveCurOrderInfo(mActivity,curOrderValues);//保存住当前接受的任务单，用于现场图片上传（先接单才上传）

		pushLayout.setVisibility(View.GONE);  //接单成功就隐藏那个任务单提示框，直接跳到导航页面
		if (BaiduNaviManager.isNaviInited()) {
			routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL,baiduLatlng);  //原生GPS坐标类型
		}

		//gxw-暂时不需要，因为一接单就跳到导航页面去了，不需要再刷新sos位置startRefreshSosLoc();
		//但是要开始实时上报自己的位置了
		MyApplication.isRecvingOrder = true; //表示已接单并且正在救助中，开始连续上报自己的位置，至于连续获取SOS求救人的位置是放在了onhidden里。因为接受任务单后
		//，势必要调到导航页，因此刷新SOS位置就没有意义了，只有回到地图首页执行onhidden时hidden = false时，去更新SOS求救人位置才是有意义的。
		addMyLocationLayer();


		return;
	}

	/**
	 * 接受任务单
	 */
	public void receiveOrder()
	{
		User user = new User(mActivity);
		String token = user.getUserToken();

		OkHttpUtils
				.post(MyConstant.API_RECEIVE_ORDER)//
				.tag(MyConstant.API_RECEIVE_ORDER)//
				.params("tokenId", token)//
				.params("itemId", mTaskOrder.getItemId())//
				.execute(new StringDialogCallback(mActivity) {
					@Override
					public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

						int retCode = response.code();
						if(retCode == 200)
						{

							Log.i(TAG,"onSuccess 200 return："+s);
							try
							{
								ReceiveOrderJson receiveOrderJson = new Gson().fromJson(s,ReceiveOrderJson.class);

								if(receiveOrderJson.getStatus() == 1)//接单成功
								{
									//登录成功
                                    dealRecvOrderOk(receiveOrderJson.getData());
								}
								else {
									 //接单失败，别人已接或者自己已接
									String msg = receiveOrderJson.getMsg();
									if(msg == null)
									{
										msg = "未知原因，接单失败";
									}

									MyErrorDeal.dealError(msg,mActivity);
								}
							}
							catch (Exception e)
							{
								e.printStackTrace();
							}
						}
						else
						{
							MyErrorDeal.dealHttpError(response,mActivity);
							Log.i(TAG,"onSuccess "+retCode+"return: "+s);
						}
					}

					@Override
					public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

						MyErrorDeal.dealHttpError(response,mActivity);

					}
				});
		return;
	}

	public void clearMarker()
	{
		mBaiduMap.clear();
		mTaskOrderList.clear();
		mOverLayOptionList.clear();

	}

	/**
	 * 更新地图上SOS呼救人的位置
	 */
	  public void updateSosLocationGui()
	{
		clearMarker();
		addMarker(); //重新标记SOS呼救人的位置
	}

	/**
	 * 刷新SOS求救者的位置
	 * @param type
	 * type=1 背后从数据库读取， type = 2请求终端实时位置
	 */
	public void refreshSosLocation(final int type)
	{
		User user = new User(mActivity);
		String token = user.getUserToken();
		MyCurrentOrder currentOrder = new MyCurrentOrder(mActivity);
		if(mTaskOrder == null)
		{
			mTaskOrder = new TaskOrder();
		}
		mTaskOrder.setDeviceIMEI(currentOrder.getDeviceIMEI());
		mTaskOrder.setSosPersonId(currentOrder.getSosPersonId());
		mTaskOrder.setItemId(currentOrder.getItemId());
		mTaskOrder.setState(currentOrder.getState());
		String deviceIMEI = mTaskOrder.getDeviceIMEI();  //设备deviceIMEI号
		if(TextUtils.isEmpty(deviceIMEI))
		{
			Log.i(TAG,"refresh sos loc return");
			return;
		}

		Log.i(TAG,"URL="+MyConstant.API_GET_SOS_LOCATION+",token="+token+",deviceIMEI="+deviceIMEI+",type="+type);
		OkHttpUtils
				.get(MyConstant.API_GET_SOS_LOCATION)//
				.tag(MyConstant.API_GET_SOS_LOCATION + type)//
				.params("tokenId", token)//
				.params("deviceIMEI", deviceIMEI)//
				.params("type", String.valueOf(type))
				.execute(new StringCallback() {
					@Override
					public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

						int retCode = response.code();
						if(retCode == 200)
						{
							Log.i(TAG,"onSuccess 200 return："+s);
							try
							{
								JSONObject sosLocation = new JSONObject(s);
								if(sosLocation.getString("status").equals("1"))  //成功响应
								{
									if (type == GET_SOSLOC_FROM_DB)  //从数据库里读取
									{
										if(mTaskOrder == null)  //如果直接new的话会覆盖掉之前mTaskOrder对象里的数据
										{
											mTaskOrder = new TaskOrder();
										}

										JSONObject data = sosLocation.getJSONObject("data");
										mTaskOrder.setDeviceIMEI(data.getString("deviceIMEI"));
										mTaskOrder.setAddress(data.getString("address"));
										mTaskOrder.setSosTime(data.getLong("locationTime"));
										mTaskOrder.setName(data.getString("name"));
										String latitude = data.getString("latitude");
										String longitude = data.getString("longitude");

										double lat = Double.parseDouble(latitude);  //gps坐标
										double lng = Double.parseDouble(longitude);//gps坐标

										LatLng baiduLatLng = BaiduMapUtils.convertGps2Map(lat,lng);  //将GPS坐标转换成百度坐标
										mTaskOrder.setLatitude(String.valueOf(baiduLatLng.latitude));
										mTaskOrder.setLongitude(String.valueOf(baiduLatLng.longitude));
										ToastUtils.showToast(mActivity,"获取SOS位置成功");
										Log.i(TAG,"获取SOS位置成功");
										updateSosLocationGui();
									}
									else if(type == GET_SOSLOC_FROM_JPUSH)  //请求实时位置，需要JPUSH推送下来
									{

										Log.i(TAG,"准备接收JPSU推送下来的求救人的 实时位置");

									}
								}

							}
							catch (Exception e)
							{
								e.printStackTrace();
							}
						}
						else
						{
							MyErrorDeal.dealHttpError(response,mActivity);
							Log.i(TAG,"onSuccess "+retCode+"return: "+s);
						}
					}

					@Override
					public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {

						Log.i(TAG,"refreshLocError"+e.getMessage());
						MyErrorDeal.dealHttpError(response,mActivity);

					}
				});
		return;
	}



	@Override
	public void onClick(View view) {

		switch(view.getId())
		{
			case R.id.ib_refresh:
				MyCurrentOrder currentOrder = new MyCurrentOrder(mActivity);
				if(currentOrder.getState() == 2)  //只有在救助中才可以索取SOS实时位置
				{
					refreshSosLocation(GET_SOSLOC_FROM_JPUSH);
				}
				else
				{
					ToastUtils.showToast(mActivity,"还没有接受任何救援任务，无法获取求救人位置");
				}

				break;
			case R.id.btMyLocation:
				MyApplication.isClickMyLoc = true;
				requestMyLocation();
				break;
			case R.id.sureRescue:   //去救援

				//先调用接单接口
				receiveOrder();
				break;
			case R.id.cancelRescue:
				mBaiduMap.clear();
                overlayManager.removeFromMap();
				pushLayout.setVisibility(View.GONE);
				break;
		}
	}

	/**
	 * 注册监听JPUSH询问位置  和  监听 JPUSH推送下来的 位置   广播
	 */
	public void registSosLocationBroadcast()
	{
	/*	IntentFilter filter = new IntentFilter();
		filter.addAction(MyConstant.receive_sos_location_action);
		filter.addAction(MyConstant.report_volunteer_location_action);
		mActivity.registerReceiver(myHomeReceiver, filter);*/
	}

	 static public class MyHomeReceiver extends BroadcastReceiver {


		public MyHomeReceiver()
		{

		}

		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				Bundle bundle = intent.getExtras();


				if (MyConstant.receive_sos_location_action.equals(intent.getAction())) {   //接收询问志愿者位置的询问命令   和  接收推送下来的SOS呼救人经纬度


					if(bundle != null)
					{
						String extraJsonStr = bundle.getString("message_extras");
						String message = bundle.getString("message");
						String title = bundle.getString("title");

						if(message.equals("1"))    //JPUSH推送下来的命令1  询问志愿者位置
						{
							mHandler.sendEmptyMessage(2);


						}
						else if(message.equals("2"))  //JPUSH 推送下来的 SOS位置
						{

							Message msg = new Message();
							msg.what = 3;
							Bundle b = new Bundle();
							b.putString("sosLoc",extraJsonStr);

							msg.setData(b);
							mHandler.sendMessage(msg); //更新SOS位置

						}

					}

				}
				else if(MyConstant.report_volunteer_location_action.equals(intent.getAction()))  //处理百度定位 的 我的位置
				{
					if(bundle != null)
					{
						double lat = bundle.getDouble("lat");
						double lng = bundle.getDouble("lng");
						float currentAccracy = bundle.getFloat("accracy");
						boolean isCenterMyLoc = bundle.getBoolean("isCenterMyLoc",false);

						Message msg = new Message();
						msg.what = 0;
						Bundle b = new Bundle();
						b.putDouble("lat",(lat));
						b.putDouble("lng",(lng));
						b.putFloat("accracy",currentAccracy);
						b.putBoolean("isCenterMyLoc",isCenterMyLoc);
						msg.setData(b);
						mHandler.sendMessage(msg); //发送位置到服务端
					}
				}
			} catch (Exception e){
				e.printStackTrace();

			}

		}

	}


}
